package org.ns.consume;

import org.ns.entity.UserInfo;
import org.ns.learn.db.autoconf.DBSourceWrapper;
import org.ns.learn.rpc.client.RpcAutowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@RestController
@RequestMapping("user")
public class UserController {

    @RpcAutowired
    UserService userService;

    @Autowired
    ApplicationContext applicationContext;

    @RequestMapping("nickname")
    public String nickname(long userId) {
        return userService.getNickName(userId);
    }

    @RequestMapping("login")
    public String login(String username, String password) {
        return userService.login(username, password);
    }
    @RequestMapping("userinfo")
    public UserInfo userinfo(long userId) {
        return userService.getUserInfo(userId);
    }

    @RequestMapping("dbsource")
    public Object dbsource(String name) {
        try {

            DBSourceWrapper dataSource = (DBSourceWrapper) applicationContext.getBean(name);
            if (dataSource.isClose()) {
                return "CLOSE";
            }

            Connection connection = dataSource.getConnection();
            PreparedStatement ps = connection.prepareStatement("select 1");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                System.out.println("sql 执行:  "+rs.getInt(1));
            }
            connection.close();
            return dataSource.getConfig();
        } catch (Exception e) {
            e.printStackTrace();
            return "NULL";
        }

    }
}
